<?php
/**
 * Ora - 后台文章管理模块
 * @author lan7
 * @copyright lan7.net
 * @version 2.0
 */
if(!defined('IN_ORA')) {
	exit('Access Denied');
}
class admin_article extends mod{
	/**
	 * 架构函数
	 *
	 * @return admin_article
	 */
	function admin_article(){
		parent::__construct();
		session_start();
		$this->setTplDir(PUBLIC_PATH);
		$this->setMsgTpl("admin/msg.html");
		if(!isset($_SESSION[$GLOBALS['ora_cfg']['sess_prefix']."admin"])){
			$this->showMsg("请先登录!",parse_uri("common-login"),1);
		}
	}

	/**
	 * 文章列表页
	 *
	 */
	function index(){
		$pid = is_numeric($GLOBALS['_param']['p'])?$GLOBALS['_param']['p']:1;
		$psize = $GLOBALS['_param']['psize']?$GLOBALS['_param']['psize']:$GLOBALS['ora_cfg']['page_size'];
		$total = $this->db->count("select count(*) from ".tn('article'));
		import("lib.page");
		$pobj = new page('p',$pid,$total,$psize);
		$sql = "select oa.*,oc.cat_name from  ".tn("article")." oa inner join ( select Id from  ".tn("article");
		$sql .= " order by Id desc limit ".$pobj->sqlParam.") b using(Id) left join ".tn("cat")." oc on oa.cat_id = oc.Id";
		if($pobj->rsort){
			$sql = "select oa.*,oc.cat_name from  ".tn("article")." oa inner join ( select Id from  ".tn("article");
			$sql .= " order by Id asc limit ".$pobj->sqlParam.") b using(Id) left join ".tn("cat")." oc on oa.cat_id = oc.Id";
		}
		$this->assign("pobj",$pobj);
		$this->assign('url',preg_replace('/\-?p(\-|\_|\=)\d+/i',"",get_urlStr()));
		$arts = $this->db->getAll($sql);
		if($pobj->rsort){
			$arts = array_reverse($arts);
		}
		$this->assign('arts',$arts);
		$this->display('admin/article.html');
	}

	/**
	 * 修改文章
	 *
	 */
	function modify(){
		$this->add();
	}

	/**
	 * 添加文章
	 *
	 */
	function add(){
		/* 获取文章类别 */
		import("lib.cat");
		$this->assign('cats',cat_lib::getSubChild(0,3,' and cat_type = 0 '));
		$id = $GLOBALS['_param']['id'];
		if(is_numeric($id)&&$id!=""){
			$sql = "select oa.*,oc.content from ".tn("article")." oa left join ".tn("content")." oc on oa.id = oc.fk_id where oc.ctype = 0  and oa.Id = $id";
			$this->assign("art",$this->db->getOne($sql));
		}
		$this->display('admin/article.html');
	}

	/**
	 * 入库更新操作
	 *
	 */
	function save(){
		$art_id = $_POST["id"];
		$title = htmlspecialchars($_POST["title"]);
		if(empty($title)||$title==""){
			$this->showMsg("动态标题不能为空!",$_SERVER["HTTP_REFERER"],1);
		}
		$source = htmlspecialchars($_POST["source"]);
		$author = htmlspecialchars($_POST["author"]);
		$keywords = htmlspecialchars($_POST["keywords"]);
		$cat_id = $_POST["cat_id"];
		if(empty($cat_id)||!is_numeric($cat_id)){
			$this->showMsg("请选择类别!",$_SERVER["HTTP_REFERER"],1);
		}
		$getWay = ($_POST["getWay"])?true:false;
		$content = $_POST["content"];
		if(empty($content)||$content == ""){
			$this->showMsg("动态内容不能为空!",$_SERVER["HTTP_REFERER"],1);
		}
		$pic = $_POST["pic"];
		if(isset($_POST["getWay"])){
			if($_POST["getWay"]=='true'){
				//重新提取
				$pic = getImg($content);
			}else{
				//本地上传
				import("lib.upload");
				$up = new Upload("jpg|gif|png");
				if(!$up->errInfo){
					$pic = $up->files[0]["urlPath"];
					import("lib.image");
					image::thumb(UPLOAD_PATH.$pic,'',$GLOBALS['ora_cfg']['thumb_width'],$GLOBALS['ora_cfg']['thumb_height']);
				}else{
					$this->showMsg("图片上传失败!",$_SERVER["HTTP_REFERER"],1);
				}
			}
		}
		$content = htmlspecialchars($content);
		$tags = $_POST["tags"];
		$tags = explode(",",$tags);
		$tags = array_map("clear_html",$tags);
		array_unique($tags);
		$tags = array_filter($tags, "loseSpace");
		$tagsstr = implode(",",$tags);
		$status = isset($_POST["status"])?1:0;
		if($art_id == "" || !is_numeric($art_id)){
			//addNew
			$sql =  "insert into ".tn("article")."(title,source,author,keywords,cat_id,pic,status,tags,dateline) ";
			$sql .= " values ('$title','$source','$author','$keywords',$cat_id,'$pic',$status,'$tagsstr',".time().")";
			$art_id = $this->db->addNew($sql);
			if(!is_numeric($art_id)){
				@io::remove(UPLOAD_PATH.$pic);//删除图片
				@io::remove(UPLOAD_PATH.timg($pic));//删除缩略图
				$this->showMsg("新增失败!",$_SERVER["HTTP_REFERER"],1);
			}else{
				$sql = "insert into ".tn("content")."(content,ctype,fk_id) values('$content',0,$art_id)";
				$this->db->execute($sql);
				/* 先清空 tags 与 Art 之间的对应关系 */
				$sql = "delete from ".tn("tags")." where tag_type = 0 and fk_id = $art_id";
				$this->db->execute($sql);
				/* 重新入库 */
				foreach ($tags as $k=>$v){
					$sql = "insert into ".tn("tags")."(tag_name,tag_type,fk_id) values('$v',0,$art_id)";
					$this->db->execute($sql);
				}
				$this->showMsg("操作成功!",parse_uri("admin_article-index"),1);
			}
		}else{
			//UpDate
			$sql = "update ".tn("article")." set title='$title',source='$source',author='$author',keywords='$keywords',cat_id=$cat_id,pic='$pic',status=$status,tags='$tagsstr' where Id = $art_id";
			$this->db->execute($sql);
			$sql = "update ".tn("content")." set content = '$content' where ctype=0 and fk_id = $art_id";
			$this->db->execute($sql);
			/* 先清空 tags 与 Art 之间的对应关系 */
			$sql = "delete from ".tn("tags")." where tag_type = 0 and fk_id = $art_id";
			$this->db->execute($sql);
			/* 重新入库 */
			foreach ($tags as $k=>$v){
				$sql = "insert into ".tn("tags")."(tag_name,tag_type,fk_id) values('$v',0,$art_id)";
				$this->db->execute($sql);
			}
			$this->showMsg("更新成功!",parse_uri("admin_article-index"),1);
		}
	}

	/**
	 * 删除文章
	 *
	 */
	function del(){
		$id = $GLOBALS['_param']['id'];
		if($id!=""&&is_numeric($id)){
			$art = $this->db->getOne("select * from ".tn("article")." where Id = $id");
			if($art){
				//删除图片
				if($art['pic']){
					@io::remove(UPLOAD_PATH.$art['pic']);
					@io::remove(UPLOAD_PATH.timg($art['pic']));
				}
				//删除标签
				$GLOBALS['db']->execute("delete from ".tn("tags")." where tag_type = 0 and fk_id = {$art['Id']}");
				//删除内容
				$GLOBALS['db']->execute("delete from ".tn("content")." where ctype = 0 and fk_id = {$art['Id']}");
				//删除文章
				$GLOBALS['db']->execute("delete from ".tn("article")." where Id = {$art['Id']}");
				$this->showMsg("删除成功!",parse_uri("admin_article-index"),1);
			}
		}else{
			$id = $_POST["id"];
			if(!empty($id)&&is_array($id)){
				foreach ($id as $k =>$v){
					delArt($v);
				}
			}
			$this->showMsg("删除成功!",parse_uri("admin_article-index"),1);
		}
	}

	/**
	 * 审核文章
	 *
	 */
	function pass(){
		$id = $_POST["id"];
		if($id!=""&&is_array($id)){
			$id = array_filter($id,"filt");
			$GLOBALS['db']->execute("update ".tn("article")." set status = 1 where Id in (".implode(",",$id).")");
			$this->showMsg("审核成功!",parse_uri("admin_article-index"),1);
		}
		$this->showMsg("请选择待审核的文章!",parse_uri("admin_article-index"),1);
	}

	/**
	 * 推荐文章
	 *
	 */
	function recommend(){
		$id = $_POST["id"];
		if($id!=""&&is_array($id)){
			$id = array_filter($id,"filt");
			$GLOBALS['db']->execute("update ".tn("article")." set status = 2 where Id in (".implode(",",$id).")");
			$this->showMsg("操作成功!",parse_uri("admin_article-index"),1);
		}
		$this->showMsg("请选择待审核的文章!",parse_uri("admin_article-index"),1);
	}


}

//************///
/** 提取图片并保存到本地 **/
function getImg(&$content){
	$tmp = array();
	if($content!=""){
		$content = stripslashes_deep($content);
		preg_match_all('/<img.*?src=["|\'](.*?)["|\'].*?\/?>/i',$content,$tmp);
		$rs = "";
		for ($j=0;$j<sizeof($tmp[1]);$j++){
			if(!empty($tmp[1][$j]) && (strpos($tmp[1][$j],HTTP_HOST)===false)){
				$imgName = rand_string(12).".jpg";
				$hdl = fopen($tmp[1][$j], "rb");
				$contents = "";
				while (!feof($hdl)) {
					$contents .= fread($hdl, 8192);
				}
				io::write(UPLOAD_PATH."http/".$imgName,$contents);
				if($rs == ""){
					$rs = $imgName;//取第一张
				}
				$content = str_replace($tmp[1][$j],HTTP_HOST."/upload/http/".$imgName,$content);
			}
		}
		$content = addslashes_deep($content);
		return "upload/http/".$rs;
	}
	return "";
}

/** 过滤空字符串 **/
function loseSpace($val){
	return (trim($val) == "")?false:true;
}
/** 删除文件及其相关数据 **/
function delArt($id){
	$art = $GLOBALS['db']->getOne("select * from ".tn("article")." where Id = $id");
	if($art){
		//删除图片
		if($art['pic']){
			@io::remove(UPLOAD_PATH.$art['pic']);
			@io::remove(UPLOAD_PATH.timg($art['pic']));
		}
		//删除标签
		$GLOBALS['db']->execute("delete from ".tn("tags")." where tag_type = 0 and fk_id = {$art['Id']}");
		//删除内容
		$GLOBALS['db']->execute("delete from ".tn("content")." where ctype = 0 and fk_id = {$art['Id']}");
		//删除文章
		$GLOBALS['db']->execute("delete from ".tn("article")." where Id = {$art['Id']}");
	}else{
		return false;
	}
}
/** 过滤非数字元素 **/
function filt($v){
	return is_numeric($v);
}

?>